//导入母版
const list = require('../template/view/list.js');
const add = require('../template/view/add.js');
const edit = require('../template/view/edit.js');
const detail = require('../template/view/detail.js');
const model = require('../template/model/model.js');
const service = require('../template/service/service.js');
const controller = require('../template/controller/controller.js');
const router = require('../template/controller/router.js');
const dva = require('../template/view/dva.js');
const api = require('../template/view/api.js');
const tool = {
    /**
     * 获取正确的表单组件
     * 
     * @param {*} html_type 
     */
    async getComponent(column, setInitValue, disable) {
        const { column_name, html_type, is_required, column_comment } = column;
        let html_type_key = "components" + html_type;
        let component = componentsSetList[html_type_key];
        let decorator = "";
        if (setInitValue) {
            decorator = `<Form.Item label="${column_comment}">
            {getFieldDecorator('${column_name}', {
                valuePropName:'${component.valuePropName}',
                initialValue: editData.${column_name},
                rules: [{ required: ${is_required == '1'}, message: '请填写${column_comment}' }],
            })(<${component.html} ${disable == true ? "disable" : ""} allowClear ></${component.html}>)}
        </Form.Item>`;
        } else {
            decorator = `<Form.Item label="${column_comment}">
            {getFieldDecorator('${column_name}', {
                valuePropName:'${component.valuePropName}',
                initialValue: ${component.initialValue},
                rules: [{ required: ${is_required == '1'}, message: '请填写${column_comment}' }],
            })(<${component.html} allowClear ></${component.html}>)}
            </Form.Item>`;
        }
        return {
            ...component,
            decorator,
        }
    },
        /**
     * 获取正确的表单组件
     * 
     * @param {*} html_type 
     */
    async getListComponent(column, setInitValue, disable) {
        const { column_name, html_type, is_required, column_comment } = column;
        let html_type_key = "components" + html_type;
        let component = componentsSetList[html_type_key];
        let decorator = "";
        if (setInitValue) {
            decorator = `<Form.Item label="${column_comment}">
            {getFieldDecorator('${column_name}', {
                valuePropName:'${component.valuePropName}',
                initialValue: editData.${column_name},
                rules: [{ message: '请填写${column_comment}' }],
            })(<${component.html} ${disable == true ? "disable" : ""} allowClear ></${component.html}>)}
        </Form.Item>`;
        } else {
            decorator = `<Form.Item label="${column_comment}">
            {getFieldDecorator('${column_name}', {
                valuePropName:'${component.valuePropName}',
                initialValue: ${component.initialValue},
                rules: [{ message: '请填写${column_comment}' }],
            })(<${component.html} allowClear ></${component.html}>)}
            </Form.Item>`;
        }
        return {
            ...component,
            decorator,
        }
    },
    /**
    * 初始化dva model页面
    * @param {*} column 
    */
    async initApi(tablename, column) {
        //开始构建
        return await api.init(tablename);
    },
   /**
    * 初始化路由
    * @param {*} column 
    */
   async initRouter(tablename, column) {
    //开始构建
    return await router.init(tablename);
    },
    /**
     * 初始化dva model页面
     * @param {*} column 
     */
    async initDvaModel(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let querySQL = [];
        let listSQL = [];
        let requiredSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
            if (item.is_required == '1') {
                requiredSQL.push(item);
            }
        }

        //得到查询的form
        let componentNames = [];
        let componentsDef = [];
        let componentsHtml = [];
        for (var i = 0; i < querySQL.length; i++) {
            let component = await tool.getComponent(querySQL[i]);
            if (component.source == "antd") {
                if (!checkInArr(componentNames, component.html)) {
                    componentNames.push(component.html);
                }
            } else {
                componentsDef.push(`\nimport ${component.html} from "${component.source}";`);
            }
            componentsHtml.push(`\n${component.decorator}`)
        }

        //开始构建
        return await dva.init(tablename, listSQL, querySQL, componentNames, componentsDef, componentsHtml, requiredSQL);
    },
    /**
     * 初始化list页面
     * @param {*} column 
     */
    async initList(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let querySQL = [];
        let listSQL = [];
        let requiredSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
            if (item.is_required == '1') {
                requiredSQL.push(item);
            }
        }

        //得到查询的form
        let componentNames = [];
        let componentsDef = [];
        let componentsHtml = [];
        for (var i = 0; i < querySQL.length; i++) {
            let component = await tool.getListComponent(querySQL[i]);
            if (component.source == "antd") {
                if (!checkInArr(componentNames, component.html)) {
                    componentNames.push(component.html);
                }
            } else {
                componentsDef.push(`\nimport ${component.html} from "${component.source}";`);
            }
            componentsHtml.push(`\n${component.decorator}`)
        }

        //开始构建
        return await list.init(tablename, listSQL, querySQL, componentNames, componentsDef, componentsHtml.join(""), requiredSQL,primaryKey);
    },
    /**
     * 初始化Add页面
     * @param {*} column 
     */
    async initAdd(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let querySQL = [];
        let listSQL = [];
        let requiredSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
            if (item.is_required == '1') {
                requiredSQL.push(item);
            }
        }

        //得到查询的form
        let componentNames = [];
        let componentsDef = [];
        let componentsHtml = [];
        let componentsHtmlRow = [];
        for (var i = 0; i < addSQL.length; i++) {
            let component = await tool.getComponent(addSQL[i]);
            if (component.source == "antd") {
                if (!checkInArr(componentNames, component.html)) {
                    componentNames.push(component.html);
                }
            } else {
                componentsDef.push(`\nimport ${component.html} from "${component.source}";`);
            }
            componentsHtmlRow.push(`
            <Col span={12}>
            ${component.decorator}
            </Col>`);

            if (componentsHtmlRow.length == 2 || (i == (addSQL.length - 1))) {
                componentsHtml.push(`
                <Row gutter={16}>
                ${componentsHtmlRow.join("")}
                </Row>`);
                componentsHtmlRow = [];
            }

        }

        //开始构建
        return await add.init(tablename, listSQL, addSQL, componentNames, componentsDef, componentsHtml.join(""), requiredSQL);
    },
    /**
     * 初始化Edit页面
     * @param {*} column 
     */
    async initEdit(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let querySQL = [];
        let listSQL = [];
        let requiredSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
            if (item.is_required == '1') {
                requiredSQL.push(item);
            }
        }

        //得到查询的form
        let componentNames = [];
        let componentsDef = [];
        let componentsHtml = [];
        let componentsHtmlRow = [];
        for (var i = 0; i < addSQL.length; i++) {
            let component = await tool.getComponent(addSQL[i], true, checkDisable(addSQL[i], editSQL));
            if (component.source == "antd") {
                if (!checkInArr(componentNames, component.html)) {
                    componentNames.push(component.html);
                }
            } else {
                componentsDef.push(`\nimport ${component.html} from "${component.source}";`);
            }
            componentsHtmlRow.push(`
            <Col span={12}>
            ${component.decorator}
            </Col>`);

            if (componentsHtmlRow.length == 2 || (i == (addSQL.length - 1))) {
                componentsHtml.push(`
                <Row gutter={16}>
                ${componentsHtmlRow.join("")}
                </Row>`);
                componentsHtmlRow = [];
            }

        }

        //开始构建
        return await edit.init(tablename, listSQL, addSQL, componentNames, componentsDef, componentsHtml.join(""), requiredSQL, primaryKey);
    },
    /**
     * 初始化Detail页面
     * @param {*} column 
     */
    async initDetail(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let detailSQL = [];
        let querySQL = [];
        let listSQL = [];
        let requiredSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_detail == '1') {
                detailSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
            if (item.is_required == '1') {
                requiredSQL.push(item);
            }
        }
        //开始构建
        return await detail.init(tablename, detailSQL, requiredSQL, primaryKey);
    },
    /**
     * 初始化Detail页面
     * @param {*} column 
     */
    async initModel(tablename, column) {
        let types = [];
        let sqColumn = [];
        for (var i = 0; i < column.length; i++) {
            let item = getModelType(column[i]);
            if (!checkInArr(types, item.model_type)) {
                types.push(item.model_type);
            }
            sqColumn.push(item.model_row);
        }
        return await model.init(tablename, types.join(","), sqColumn.join(" "));
    },
    /**
     * 初始化Service
     * @param {*} column 
     */
    async initService(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let querySQL = [];
        let listSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
        }
        //开始构建
        return await service.init(tablename, primaryKey, column, addSQL, editSQL, querySQL, listSQL);
    },
    /**
     * 初始化Controller
     * @param {*} column 
     */
    async initController(tablename, column) {
        //构建动态sql字段,表的别名默认为 "t"
        let primaryKey = {};
        let addSQL = [];
        let editSQL = [];
        let querySQL = [];
        let listSQL = [];
        let requiredSQL = [];
        for (var i = 0; i < column.length; i++) {
            let item = column[i];
            if (item.is_add == '1') {
                addSQL.push(item);
            }
            if (item.is_edit == '1') {
                editSQL.push(item);
            }
            if (item.is_list == '1') {
                listSQL.push(item);
            }
            if (item.is_query == '1') {
                querySQL.push(item);
            }
            if (item.t_column_key == 'PRI') {
                primaryKey = item;
            }
            if (item.is_required == '1') {
                requiredSQL.push(item);
            }
        }
        //开始构建
        return await controller.init(tablename, primaryKey, column, addSQL, editSQL, querySQL, listSQL, requiredSQL);
    }
}
module.exports = tool;

//定义所有表单组件的属性值
const componentsSetList = {
    //文本框 
    "components01": {
        source: "antd",
        html: "Input",//使用的组件标签
        valuePropName: "value",//表单赋值的key
        initialValue: "''"//初始化值，部分可能是数组
    },
    //数字输入框 
    "components02": {
        source: "antd",
        html: "InputNumber",
        valuePropName: "value",
        initialValue: "''"
    },
    //文本域
    "components03": {
        source: "antd",
        html: "Input.TextArea",
        valuePropName: "value",
        initialValue: "''"
    },
    //开关
    "components04": {
        source: "antd",
        html: "Switch",
        valuePropName: "checked",
        initialValue: false
    },
    //复选框
    "components05": {
        source: "antd",
        html: "Checkbox.Group",
        valuePropName: "checked",
        initialValue: false
    },
    //单选框 
    "components06": {
        source: "antd",
        html: "Radio.Group",
        valuePropName: "checked",
        initialValue: false
    },
    //下拉框 
    "components07": {
        source: "antd",
        html: "Select",
        valuePropName: "value",
        initialValue: '[]'
    },
    //下拉多选框
    "components08": {
        source: "antd",
        html: "Select",
        valuePropName: "value",
        initialValue: '[]'
    },
    //级联选择框
    "components09": {
        source: "antd",
        html: "Cascader",
        valuePropName: "value",
        initialValue: '[]'
    },
    //树形选择框
    "components10": {
        source: "antd",
        html: "TreeSelect",
        valuePropName: "value",
        initialValue: '[]'
    },
    //日期选择框 
    "components11": {
        source: "antd",
        html: "DatePicker",
        valuePropName: "value",
        initialValue: "''"
    },
    //时间选择框
    "components12": {
        source: "antd",
        html: "TimePicker",
        valuePropName: "value",
        initialValue: "''"
    },
    //图片上传
    "components13": {
        source: "components/upload/MulPic",
        html: "MulPic",
        valuePropName: "value",
        initialValue: '[]'
    },
    //文件上传
    "components14": {
        source: "components/upload/MulFile",
        html: "MulFile",
        valuePropName: "value",
        initialValue: '[]'
    },
    //富文本
    "components15": {
        source: "components/form/Editer",
        html: "Editer",
        valuePropName: "value",
        initialValue: "''"
    },
}

/**
 * 检查字符串是否存在一个字符串中
 * @param {*} arraylist 
 * @param {*} str 
 */
function checkInArr(arraylist, str) {
    for (var i = 0; i < arraylist.length; i++) {
        if (arraylist[i] == str) {
            return true;
        }
    }
    return false;
}

/**
 * 生成标准数据类型
 * @param {*} arraylist 
 * @param {*} str 
 */
function getModelType(columnRow) {
    //得到model类型
    let model_type_upperCase = columnRow.model_type.toUpperCase();
    let model_type = "";
    if (columnRow.model_type == "Date" || columnRow.model_type == "UUID" || columnRow.model_type == "Integer") {
        model_type = `type: ${model_type_upperCase}`;
    } else {
        model_type = `type: ${model_type_upperCase}(${columnRow.model_long})`;
    }
    //是否主键
    let PRI = "";
    if (columnRow.t_column_key == "PRI") {
        PRI = ", primaryKey: true";
    }
    //是否自增
    let auto_increment = "";
    if (columnRow.t_column_extra == "auto_increment") {
        auto_increment = ", autoIncrement: true";
    }

    let row = `${columnRow.t_column_name}: { ${model_type}${PRI}${auto_increment} },//${columnRow.column_comment}`;
    return { model_row: `\r\n\t\t` + row, model_type: model_type_upperCase };
}

/**
 * 是否允许编辑
 * @param {*} item 
 * @param {*} editData 
 */
function checkDisable(item, editSQL) {
    for (var i = 0; i < editSQL.length; i++) {
        if (item.t_column_name == editSQL[i].t_column_name) {
            return false;
        }
    }
    return true;
}